package com.ethan.simplesms.controller;

import com.ethan.simplesms.req.SmsReq;
import com.ethan.simplesms.service.SendService;
import com.ethan.simplesms.untils.CommonUtil;
import com.ethan.simplesms.untils.R;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @Description:
 * @Author ethan
 * @CreateDate: 2022/05/29 上午8:22
 * @UpdateDate: 2022/05/29 上午8:22
 * @Version 1.0
 */
@RestController
@RequestMapping("sms")
@Slf4j
public class SmsController {

    @Autowired
    DefaultKaptcha captchaProducer;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    SendService sendService;

    @GetMapping("kaptcha")
    public void kaptcha(HttpServletRequest request, HttpServletResponse response){
        String captchaText = captchaProducer.createText();
        log.info("验证码内容:{}",captchaText);

        //存储redis,配置过期时间 ， jedis/lettuce
        redisTemplate.opsForValue().set(getCaptchaKey(request),captchaText,60*1000, TimeUnit.MILLISECONDS);

        BufferedImage bufferedImage = captchaProducer.createImage(captchaText);

        try (ServletOutputStream outputStream = response.getOutputStream()){

            ImageIO.write(bufferedImage,"jpg",outputStream);
            outputStream.flush();

        } catch (IOException e) {
            log.error("获取流出错:{}",e.getMessage());
        }
        return;
    }
    @PostMapping("send_code")
    public R send(HttpServletRequest request, @RequestBody SmsReq smsReq){
        String key = getCaptchaKey(request);
        String cacheCacha = redisTemplate.opsForValue().get(key);

        if (!StringUtils.isEmpty(cacheCacha)&&cacheCacha.equalsIgnoreCase(smsReq.getCatcha())){
            redisTemplate.delete(key);
            return sendService.send(smsReq.getTel());
        }else{
            return R.error(-1,"图形验证码错误");
        }

    }
    /**
     * 根据浏览器明细获取key
     *
     * @param request
     * @return
     */
    private String getCaptchaKey(HttpServletRequest request) {
        String ip = CommonUtil.getIpAddress(request);
        String userAgent = request.getHeader("User-Agent");
        String key = "sms-service:captcha:" + CommonUtil.MD5(ip + userAgent);
        log.info("图形验证码key:{}", key);
        return key;
    }
}
